#!/bin/bash
#文件名： checkTicket.sh
#用途：从12306获得票的余量信息

echoInfor()
{
#	echo $1 $2 $3
#	echo 进入函数
	if [ $1 -eq 1 ];
	then
#		echo 查看是否忽略
		[[ $3 != "未开设" ]] && [[ $3 != "无" ]] && echo $2:$3
	else
		echo $2:$3
	fi	
	return 0;
}


ignore=0
optind=0;
while getopts "::hi" opt
do
	case $opt in
	h )
		echo -i 忽略未设置和没有余量的位置信息
		exit 1;;
	i )
	#	echo 设置忽略
	#	echo $optind
		let "optind++"
		ignore=1;;
	esac
done

#echo $optind
shift $(($optind))
if [ $# -lt 3 ];
then
	echo 用法：$0 时间年份-月份-日期 起点站 终点站
fi
#爬取城市对应代号
response=`curl https://kyfw.12306.cn/otn/resources/js/framework/station_name.js?station_version=1.9018 -slient`
city1=`echo $response | egrep -o "$2\|[A-Z]+" |cut -d"|" -f2`
city2=`echo $response | egrep -o "$3\|[A-Z]+" |cut -d"|" -f2`
#echo $city1
#爬取核心数据段
response=`curl  "https://kyfw.12306.cn/otn/leftTicket/queryZ?leftTicketDTO.train_date=$1&leftTicketDTO.from_station=$city1&leftTicketDTO.to_station=$city2&purpose_codes=0X00" -slient| egrep -o "\[[^]]+" ` #"result[:|\||\"|a-z|A-Z|0-9|:|\[|%]+"`
#去掉前面的一个引号
response=`echo $response | cut -c 2-  ` # | sed "s:,:\r:g"`
#按照句号分割到数组中
OLD_IFS="$IFS"
IFS=","
arr=($response)
IFS="$OLD_IFS"
for s in ${arr[@]}
do
	OLD_IFS="$IFS"
#	echo s is $s
	s=`echo $s | sed 's/||/|未开设|/g'`		
	s=`echo $s | sed 's/||/|未开设|/g'`	
#	echo "the value of s is $s"
	IFS="|"
	train=($s)
	IFS="$OLD_IFS"
	i=0
#	for item in ${train[@]}
#	do
#		echo 第$i项的值是$item
	echo 车次:${train[3]}
	echo 出发时间:${train[8]}
	echo 到达时间:${train[9]}
	echo 历时:${train[10]}
	echoInfor $ignore "商务座" ${train[32]}
	echoInfor $ignore "一等座" ${train[31]}
	echoInfor $ignore "二等座" ${train[30]}
	echoInfor $ignore "高级软卧" ${train[21]}
	echoInfor $ignore "软卧" ${train[23]}
	echoInfor $ignore "硬卧" ${train[28]}
	echoInfor $ignore "软座" ${train[24]}
	echoInfor $ignore "硬座" ${train[29]}
	echoInfor $ignore "无座" ${train[26]}
	echo 	
#	let "i++"	
#	done
done	
